<template>
  <div class="spec-preview">
    <img :src="imgUrl" ref="showImg" />
    <div class="event" @mousemove="mouseenterFn" ref="event"></div>
    <div class="big">
      <img :src="imgUrl" ref="bigImg" />
    </div>
    <div class="mask" ref="mask"></div>
  </div>
</template>

<script>
import { getRealoffset } from '@/utils/utils'
import throttle from 'lodash/throttle'
export default {
  name: 'ZZoom',
  data() {
    return {
      position: {
        top: 0,
        left: 0,
      },
    }
  },
  props: {
    imgUrl: String,
  },
  mounted() {
    this.$bus.$on('change-img', this.changeImg)
    // const { top, left } = getRealoffset(this.$refs.event)
    // this.position.top = top
    // this.position.left = left
  },
  methods: {
    mouseenterFn: throttle(function (e) {
      const { top: realTop, left: realLeft } = getRealoffset(this.$refs.event)
      this.position.top = realTop
      this.position.left = realLeft
      // 鼠标移入，计算鼠标在框内的坐标 （页面的坐标（pageX,pageY） - 框的坐标(offsetLeft,offsetTop)）
      // 计算出mask框的坐标
      const mask = this.$refs.mask
      const event = this.$refs.event
      const bigImg = this.$refs.bigImg
      let left = e.pageX - this.position.left - mask.offsetWidth / 2
      left = Math.min(left, event.offsetWidth - mask.offsetWidth)
      left = Math.max(left, 0)
      let top = e.pageY - this.position.top - mask.offsetHeight / 2
      top = Math.min(top, event.offsetHeight - mask.offsetHeight)
      top = Math.max(top, 0)
      //小框的位置
      mask.style.left = left + 'px'
      mask.style.top = top + 'px'
      // 大图片的位置
      bigImg.style.left =
        -left * (bigImg.offsetWidth / event.offsetWidth) + 'px'
      bigImg.style.top =
        -top * (bigImg.offsetHeight / event.offsetHeight) + 'px'
    }, 20),
    changeImg(url) {
      this.$refs.showImg.src = url
      this.$refs.bigImg.src = url
    },
  },
  beforeDestroy() {
    this.$bus.$off('change-img')
  },
}
</script>

<style lang="less">
.spec-preview {
  position: relative;
  width: 400px;
  height: 400px;
  border: 1px solid #ccc;

  img {
    width: 100%;
    height: 100%;
  }

  .event {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0px;
    left: 0;
    z-index: 998;
  }

  .mask {
    width: 50%;
    height: 50%;
    background-color: rgba(0, 255, 0, 0.3);
    position: absolute;
    left: 0;
    top: 0;
    display: none;
  }

  .big {
    width: 100%;
    height: 100%;
    position: absolute;
    top: -1px;
    left: 100%;
    border: 1px solid #aaa;
    overflow: hidden;
    z-index: 998;
    display: none;
    background: white;

    img {
      width: 200%;
      max-width: 200%;
      height: 200%;
      position: absolute;
      left: 0;
      top: 0;
    }
  }

  .event:hover ~ .mask,
  .event:hover ~ .big {
    display: block;
  }
}
</style>
